import requests
import logging
import os
from utils import zytoken, zymysql


# 设置日志配置
current_dir = os.path.dirname(os.path.abspath(__file__))
target_dir = os.path.join(os.path.dirname(current_dir), "logs")  # 子目录名称
log_filename = os.path.join(target_dir, "attendance_record.log")
logging.basicConfig(
    level=logging.INFO,  # 设置日志级别为INFO
    format='%(asctime)s - %(levelname)s - %(message)s',  # 设置日志格式
    handlers=[
        logging.FileHandler(log_filename),  # 将日志写入文件
        logging.StreamHandler()  # 也打印到控制台
    ]
)

def pending(id):
    url = 'http://192.168.0.13:4865/seeyon/rest/affairs/pending?ticket=djnode&memberId=-8409815201310029713&apps=1'
    header = {"token": zytoken.getzytoken()}
    re = requests.get(url, header)
    dat = re.json()['data']
    print("id",id)
    sql = 'select ctp_affair.OBJECT_ID from ctp_affair where id=' + str(id)
    try:
        objectId = zymysql.seeyon_query(sql)[0][0]
    except:
        objectId= id
    if dat != []:
        for i in dat:
            if i['objectId'] == int(objectId):
                workitemId = i['subObjectId']
                return workitemId
        return '未查询到事项ID'
    else:
        return '未查询到事项ID'

def stepBack(id,mange):
    url1 = 'http://192.168.0.13:4865/seeyon/rest/bpm/workitem/stepBack'
    data = {
        "appName": "collaboration",
        "workitemId": id,
        "data":
            {
                "comment_deal": {
                    "attitude": "3",
                    "content": mange
                },
                "isWFTrace": "0"
            }
    }
    requests.post(url1, json=data, headers=zytoken.shen_header())


def finish(id,mange):
    url1 = 'http://192.168.0.13:4865/seeyon/rest/bpm/workitem/finish'
    dat = {
        "appName": "collaboration",
        "workitemId": id ,
        "data": {
            "comment_deal": {
                "attitude": "2",
                "content": mange
            },
            "submitType": "1",
            "baseProcessXML": "",
            "baseReadyObjectJSON": "",
            "messageDataList": "",
            "changeMessageJSON": ""
        }
    }
    print(dat)
    requests.post(url1, json=dat, headers=zytoken.shen_header())


def start(id,float,mange):
    workitem_Id = pending(id)
    print("workitem_Id",workitem_Id)
    if workitem_Id != '未查询到事项ID':
        if float==True:
            finish(workitem_Id,mange)
            logging.info(f"协同通过workitem_Id{workitem_Id}")
        elif float==False:
            stepBack(workitem_Id,mange)
            logging.error(f"错误回退workitem_Id{workitem_Id}")
    else:
        print('回退失败，具体原因待查看')
        logging.error(f'{id}回退或审批失败，具体原因待查看')



if __name__ == '__main__':
    pending("5237691625948268263")
    # id  = "-8705326366004655219"
    # start(id, True, '同意')